<?php
namespace app\admin\model;
use think\Model;
use think\Db;
use app\admin\model\NoteM;
use app\admin\model\Signm;

/**
 * 渠道对接通道表模型
 * @package app\admin\model
 */
class CorrespondM extends Model
{
	// 设置当前模型对应的完整数据表名称
    protected $table = 'bus_correspond';

    public function getCorrespondAll($request=[])
    {
        $data = $this->alias('cor')
            ->field('cor.*,cha.company_name,pla.platfrom,pla.plat_group,ope.desc,sign.sign,note.notes,cous.correspond_count')
            ->join('bus_channel cha','cha.channel_id = cor.cid','LEFT')
            ->join('bus_platfrom pla','pla.plat_id = cor.plat_id','LEFT')
            ->join('main_operator ope','ope.code = cor.isp_host','LEFT')
            ->join('bus_note note','note.id = cor.channel_sms_id','LEFT')
            ->join('bus_sign sign','sign.id = note.sign_id','LEFT')
            ->join('(select count(id) correspond_count,correspond_id from bus_plat_group_config group by correspond_id) cous','cor.id = cous.correspond_id','LEFT');

        if(!empty($request['sign'])) {

            $data = $data->where('sign.sign', 'like' , '%' . $request['sign'] . '%' );
        }
        if(!empty($request['ci'])) {

            $data = $data->where('cor.cid',$request['ci']);
        }

        if(!empty($request['pi'])) {

            $data = $data->where('cor.plat_id',$request['pi']);
        }

        if(session('username') == 'admin2018') {

            $data = $data->where('cor.create_user','admin2018');
        }

        $data = $data->order('cor.cid , cor.channel_sms_id')
    		->paginate($request['limit'], false, ['query' => $request])
            ->each(function($item, $key) {

                // $note = NoteM::field('sign_id,notes')->where('id',$item->channel_sms_id)->find();
                // $sign = Signm::field('sign')->where('id',$note['sign_id'])->find();

                $item->neirong = $item->sign . $item->notes;

                if($item->plat_group == 'GROUP')
                {
                    if(empty($item->correspond_count)){
                        $item->correspond_count = 0;
                    }
                    $item->correspond_count = '<a href="javascript:;" style="color:#01499C" onclick="onOpenRoute('.$item->id.','.$item->plat_id.')">配置('.$item->correspond_count.')</a>';
                }else{
                    $item->correspond_count = '<a href="javascript:;" style="color:#ccc" >配置(0)</a>';
                }

                switch ($item->on_off) {
                    case '0':
                        $item->on = '<span class="layui-badge status-jy">已禁用</span>';
                        break;
                    case '1':
                        $item->on = '<span class="layui-badge layui-bg-green status-qy">已启用</span>';
                        break;

                    default:
                        # code...
                        break;
                }
            });

    	return $data;
    }

    /**
     * 渠道配置通道
     * @Author   lf
     * @DateTime 2018-07-04T10:34:59+0800
     * @param    [type]                   $channel_id [渠道id]
     * @param    [type]                   $plat_id    [通道id]
     * @param    [type]                   $operator   [运营商]
     */
    public function addCCPOne($channel_id,$plat_id,$operator,$chasmsid,$plasmsid,$port_number,$type)
    {
    	try {

            $add['cid']            = $channel_id;
            $add['plat_id']        = $plat_id;
            $add['isp_host']       = $operator;
            $add['channel_sms_id'] = $chasmsid;
            $add['plat_bus_id']    = $plasmsid;
            $add['on_off']         = '0';
            $add['create_time']    = date('Y-m-d H:i:s');
            $add['create_user']    = session('username');
            $add['user']           = session('username');
            $add['update_time']    = date('Y-m-d H:i:s');
            $add['port_number']   = $port_number;
            $add['type']   = $type;
	    	$this->isUpdate(false)->save($add);

	    	trace('【通道配置】'.session('username').'新增渠道对接通道信息：'.json_encode($add,JSON_UNESCAPED_UNICODE),'info');
	    	echo "success";

    	} catch (Exception $e) {

    		trace('【通道配置】'.session('username').'添加渠道对接错误，'.$e,'error');
    		echo "添加失败，服务繁忙";
    	}
    }

    /**
     * 开关
     * @Author   lf
     * @DateTime 2018-07-04T11:07:57+0800
     * @param    [type]                   $ccpid [记录id]
     * @param    [type]                   $sta   [状态]
     */
    public function addCCPOnOff($ccpid,$sta)
    {
        try {
            $ccpid = json_decode($ccpid,true);

            $this->where('id','in',$ccpid)->update([
                    "on_off" => $sta
                    ,"user" => session('username')
                    ,"update_time" => date('Y-m-d H:i:s')
                ]);

            if($sta == '1'){
                trace('【通道配置】'.session('username').'开启渠道：'.json_encode($ccpid,JSON_UNESCAPED_UNICODE),'info');
            }else{
                trace('【通道配置】'.session('username').'关闭渠道：'.json_encode($ccpid,JSON_UNESCAPED_UNICODE),'info');
            }

            return json(['code'=>1,'msg'=> $sta ? '开启成功' : '禁用成功']);

        } catch (Exception $e) {

            return json(['code'=>0,'msg'=> '失败']);

            trace('【通道配置】'.session('username').'开关渠道对接错误，'.$e,'error');
            echo "开关失败，服务繁忙";
        }
    }

    /**
     * 修改配置
     * @Author   lf
     * @DateTime 2018-07-04T14:20:55+0800
     * @param    [type]                   $ccpid [description]
     * @param    [type]                   $pi    [description]
     */
    public function setCCPEdit($ccpid,$pi,$plasmsid,$port_number,$type)
    {
        try {
            $ccpm = CorrespondM::get($ccpid);

            //切换通道关闭分省路由
            if($ccpm->plat_id != $pi)
            {
                $upnum = Db::table('bus_plat_group_config')
                    ->where('correspond_id',$ccpm->id)
                    ->where('plat_id',$ccpm->plat_id)
                    ->where('route_flag',1)
                    ->update(['onoff'=>0]);
                if($upnum > 0){
                    deleteCache('GROUPCONFIG');
                }
                trace('涉及切换通道，已关闭原通道的指定省份分省路由'.$upnum."条",'info');
            }

            $plat_yuan = $ccpm;

            // $ccpm->plat_id        = $pi;
            // $ccpm->plat_bus_id    = $plasmsid;
            // $ccpm->user           = session('username');
            // $ccpm->update_time    = date('Y-m-d H:i:s');
            // $ccpm->port_number    = $port_number;
            // $ccpm['type']         = (int)$type;
            $data = ['plat_id'=>$pi,'plat_bus_id'=>$plasmsid,'user'=>session('username'),'update_time'=>date('Y-m-d H:i:s'),'port_number'=>$port_number,'type'=>$type];
            $ccpm->isUpdate(true)->save($data);

            trace('【通道配置】'.session('username')."修改配置\r\n由".json_encode($plat_yuan,JSON_UNESCAPED_UNICODE)."\r\n改为".json_encode($ccpm,JSON_UNESCAPED_UNICODE),'info');
            echo "success";

        } catch (Exception $e) {

            trace('【通道配置】'.session('username')."修改配置失败".$e,'error');
            echo "修改配置失败，服务繁忙";
        }
    }

}